import React, { Component } from 'react';
import BpmnViewer from 'bpmn-js/lib/Viewer';
// 自定义画板
import customRenderer from '../../components/BsinBpmnModeler/customRender/index.js';
// 翻译成中文的模板
import customTranslate from '../../components/BsinBpmnModeler/customTranslate/customTranslate';
import './index.css';
import flowableModdle from './flowable.json';
// 导入数据  可以从后台获取
import { xmlStr } from '../../mock/xmlStr.js';
import { getModelById } from '../../services/modelDefinition';
import { getHistoryActInst } from '../../services/processTask';
import { message } from 'antd';

class ModelView extends Component {
  constructor(props) {
    super(props);
  }

  state = { xml: null };
  /**
   *  生命周期
   * componentDidMount组件加载完毕
   */
  componentDidMount() {
    this.init();
  }

  // 获取xml信息
  getXml = async () => {};

  init = () => {
    // 类组件获取元素
    const canvas = this.canvas;
    // 将汉化包装成一个模块
    const customTranslateModule = {
      translate: ['value', customTranslate],
    };
    //  初始化实例
    this.bpmnViewer = new BpmnViewer({
      // 兼容flowable
      moddleExtensions: {
        flowable: flowableModdle,
      },
      // 元素容器
      container: canvas,
      additionalModules: [
        // // 自定义画板
        // customRenderer,
        // // 汉化模块
        customTranslateModule,
      ],
    });
    // 调用渲染
    this.createNewDiagram();
  };

  /**
   * 渲染,把数据添加进框
   */
  createNewDiagram = async () => {
    setTimeout(() => {
      // 隐藏图标
      document.getElementsByClassName('bjs-powered-by')[0].style.display =
        'none';
    }, 500);
    let xml = xmlStr;
    if (this.props.processDefinitionId) {
      let res = await getModelById({
        processDefinitionId: this.props.processDefinitionId,
      });
      if (res.code !== '000000') {
        return message.error('获取流程信息失败');
      }
      xml = res.data;
    }
    // 这是一个promise对象
    // 官方原来的例子是回调函数,但是说以后会取消
    this.bpmnViewer.importXML(xml).then(async () => {
      let id = '';
      if (this.props.processInstanceId) {
        let res = await getHistoryActInst({
          processInstanceId: this.props.processInstanceId,
        });
        if (res.code !== '000000') {
          return message.error('获取流程信息失败');
        }
        id = res.data[res.data.length - 1].activityId;
      }
      // 居中自适应
      const canvas = this.bpmnViewer.get('canvas');
      if (id) {
        canvas.addMarker(id, 'bag');
      }
      canvas.zoom('fit-viewport', 'auto');
    });
  };

  render() {
    return (
      <div className="viewer-container" style={{ position: 'relative' }}>
        <div
          className="viewer-canvas"
          ref={(c) => (this.canvas = c)}
          style={{ height: 600 }}
        ></div>
      </div>
    );
  }
}

export default ModelView;
